package com.hzw.saas.service.project.flow.service;

import cn.hutool.core.lang.Assert;
import com.hzw.saas.api.storage.IResourceFileService;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.flow.exception.FlowServiceHandleException;
import com.hzw.saas.common.flow.pojo.model.FlowInstance;
import com.hzw.saas.common.flow.pojo.model.FlowProcessRecord;
import com.hzw.saas.common.flow.service.FlowActionHandle;
import com.hzw.saas.common.util.enums.AssertEnum;
import com.hzw.saas.service.project.bo.ProjectApplyBO;
import com.hzw.saas.service.project.constants.ProjectConsts;
import com.hzw.saas.service.project.enums.AttachmentType;
import com.hzw.saas.service.project.service.IProjectApplyService;
import com.hzw.saas.service.project.service.IProjectAttachmentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zzl
 * @since 08/13/2021
 */
@Service(ProjectConsts.PROJECT_ACCEPTANCE_APPLY_SUBMIT)
@RequiredArgsConstructor
@Slf4j
public class ProjectAcceptanceApplySubmitImpl implements FlowActionHandle {

    private final IProjectApplyService projectApplyService;
    private final IProjectAttachmentService projectAttachmentService;
    private final IResourceFileService resourceFileService;

    @Override
    public void handle(FlowInstance flowInstance, FlowProcessRecord flowProcessRecord) throws FlowServiceHandleException {
        ProjectApplyBO projectApply = projectApplyService.getProjectApply(flowProcessRecord.getFlowInstanceId(), null);
        AssertUtil.assertExistence(AssertEnum.FOUND, projectApply, "项目申请");
        // 校验验收申请说明<=2000字
        Assert.notBlank(projectApply.getAcceptanceInstruction(), "项目验收申请说明为空");
        Assert.isTrue(projectApply.getAcceptanceInstruction().length() <= 2000, "项目验收申请说明不可超过2000字");
        // 校验验收申请附件 最大个数10，最大文件大小50M
        List<String> attachmentIds = projectAttachmentService.listProjectAttachmentIds(projectApply.getPid(),
            AttachmentType.ACCEPTANCE_INSTRUCTION.code(), AttachmentType.ACCEPTANCE_REPORT.code(),
            AttachmentType.RESEARCH_PAPER.code(), AttachmentType.PROJECT_CONTRACT.code(), AttachmentType.CALCULATE_DATA.code());
        long totalSize = resourceFileService.countSizeBySupId(attachmentIds, null, null);
        Assert.isTrue(attachmentIds.size() <= ProjectConsts.MAX_ACCEPTANCE_ATTACHMENT_COUNT,
            "文件总个数不可超过" + ProjectConsts.MAX_ACCEPTANCE_ATTACHMENT_COUNT);
        Assert.isTrue(totalSize <= ProjectConsts.MAX_ACCEPTANCE_ATTACHMENT_SIZE,
            "文件总大小不可超过50M");
    }

}
